<?php
/**
 * 用户相关API
 * 处理用户登录、注册、个人资料等功能
 */

require_once __DIR__ . '/ApiHandler.php';

class UserApi extends ApiHandler {
    
    /**
     * 处理GET请求
     * 获取用户信息
     */
    protected function GET() {
        // 验证用户登录
        if (!$this->validateAccess()) {
            return;
        }
        
        $userId = $this->user->getUserId();
        
        // 获取基本用户信息
        $userData = $this->user->getUserData();
        
        // 移除敏感信息
        unset($userData['password']);
        
        // 获取用户详细资料
        $sql = "SELECT * FROM " . DB_PREFIX . "user_profiles WHERE user_id = ?";
        $profile = $this->db->fetchRow($sql, [$userId]);
        
        if ($profile) {
            $userData['profile'] = $profile;
        }
        
        // 获取用户成就统计
        $sql = "SELECT COUNT(*) FROM " . DB_PREFIX . "user_achievements WHERE user_id = ?";
        $achievementCount = $this->db->fetchOne($sql, [$userId]);
        $userData['achievement_count'] = (int)$achievementCount;
        
        // 获取用户游戏进度统计
        $sql = "SELECT COUNT(*) FROM " . DB_PREFIX . "user_game_progress WHERE user_id = ?";
        $gameProgressCount = $this->db->fetchOne($sql, [$userId]);
        $userData['games_played'] = (int)$gameProgressCount;
        
        // 获取用户的星星总数
        $sql = "SELECT SUM(stars) FROM " . DB_PREFIX . "user_game_progress WHERE user_id = ?";
        $totalStars = $this->db->fetchOne($sql, [$userId]);
        $userData['total_stars'] = (int)($totalStars ?? 0);
        
        $this->sendResponse(['success' => true, 'user' => $userData]);
    }
    
    /**
     * 处理POST请求
     * 用户登录或注册
     */
    protected function POST() {
        $action = $this->getParam('action', '');
        
        switch ($action) {
            case 'login':
                $this->login();
                break;
            case 'register':
                $this->register();
                break;
            case 'logout':
                $this->logout();
                break;
            case 'update_profile':
                $this->updateProfile();
                break;
            case 'change_password':
                $this->changePassword();
                break;
            default:
                $this->sendResponse(['error' => 'Invalid action'], 400);
                break;
        }
    }
    
    /**
     * 用户登录
     */
    private function login() {
        // 验证必填参数
        if (!$this->validateRequiredParams(['username', 'password'])) {
            return;
        }
        
        $username = $this->getParam('username');
        $password = $this->getParam('password');
        
        if ($this->user->login($username, $password)) {
            $userData = $this->user->getUserData();
            
            // 移除敏感信息
            unset($userData['password']);
            
            $this->sendResponse([
                'success' => true,
                'message' => '登录成功',
                'user' => $userData
            ]);
        } else {
            $this->sendResponse([
                'success' => false,
                'message' => '用户名或密码错误'
            ], 401);
        }
    }
    
    /**
     * 用户注册
     */
    private function register() {
        // 验证必填参数
        if (!$this->validateRequiredParams(['username', 'email', 'password'])) {
            return;
        }
        
        $userData = [
            'username' => $this->getParam('username'),
            'email' => $this->getParam('email'),
            'password' => $this->getParam('password'),
            'child_name' => $this->getParam('child_name', ''),
            'child_age' => (int)$this->getParam('child_age', 0)
        ];
        
        // 验证邮箱格式
        if (!filter_var($userData['email'], FILTER_VALIDATE_EMAIL)) {
            $this->sendResponse([
                'success' => false,
                'message' => '邮箱格式不正确'
            ], 400);
            return;
        }
        
        // 验证密码长度
        if (strlen($userData['password']) < 6) {
            $this->sendResponse([
                'success' => false,
                'message' => '密码长度至少为6位'
            ], 400);
            return;
        }
        
        $result = $this->user->register($userData);
        
        if ($result['success']) {
            $this->sendResponse([
                'success' => true,
                'message' => '注册成功',
                'user_id' => $result['user_id']
            ]);
        } else {
            $this->sendResponse([
                'success' => false,
                'message' => $result['message']
            ], 400);
        }
    }
    
    /**
     * 用户登出
     */
    private function logout() {
        $this->user->logout();
        $this->sendResponse([
            'success' => true,
            'message' => '已登出系统'
        ]);
    }
    
    /**
     * 更新用户资料
     */
    private function updateProfile() {
        // 验证用户登录
        if (!$this->validateAccess()) {
            return;
        }
        
        $data = [
            'email' => $this->getParam('email'),
            'username' => $this->getParam('username'),
            'child_name' => $this->getParam('child_name'),
            'child_age' => $this->getParam('child_age')
        ];
        
        // 移除未设置的字段
        foreach ($data as $key => $value) {
            if ($value === null) {
                unset($data[$key]);
            }
        }
        
        // 验证邮箱格式
        if (isset($data['email']) && !filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
            $this->sendResponse([
                'success' => false,
                'message' => '邮箱格式不正确'
            ], 400);
            return;
        }
        
        if ($this->user->updateProfile($data)) {
            $this->sendResponse([
                'success' => true,
                'message' => '资料更新成功'
            ]);
        } else {
            $this->sendResponse([
                'success' => false,
                'message' => '资料更新失败'
            ], 500);
        }
    }
    
    /**
     * 修改密码
     */
    private function changePassword() {
        // 验证用户登录
        if (!$this->validateAccess()) {
            return;
        }
        
        // 验证必填参数
        if (!$this->validateRequiredParams(['current_password', 'new_password'])) {
            return;
        }
        
        $currentPassword = $this->getParam('current_password');
        $newPassword = $this->getParam('new_password');
        
        // 验证新密码长度
        if (strlen($newPassword) < 6) {
            $this->sendResponse([
                'success' => false,
                'message' => '新密码长度至少为6位'
            ], 400);
            return;
        }
        
        if ($this->user->changePassword($currentPassword, $newPassword)) {
            $this->sendResponse([
                'success' => true,
                'message' => '密码修改成功'
            ]);
        } else {
            $this->sendResponse([
                'success' => false,
                'message' => '当前密码错误或密码修改失败'
            ], 400);
        }
    }
}

// 创建API实例并处理请求
$api = new UserApi('users');
$api->processRequest(); 